package com.martin.permission;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

/**
 * @Author: martin
 * @CreateDate: 2021/9/15
 * @Description:
 */
public class PermissionModule extends UniModule {
    private UniJSCallback jsCallBack;
    public static final String TAG = "PermissionModule";

    @UniJSMethod
    public void toFileSetting() {
        Context context = mUniSDKInstance.getContext();
        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    @UniJSMethod
    public void toWifiSetting() {
        Context context = mUniSDKInstance.getContext();
        Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
        context.startActivity(intent);
    }

    @UniJSMethod
    public void chooseFile(UniJSCallback _jsCallback) {
        jsCallBack = _jsCallback;
        if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
            Activity activity = (Activity) mUniSDKInstance.getContext();
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            activity.startActivityForResult(intent, 1000);
        } else {
            Log.e(TAG, "getFile: 获取文件 失败 === 不是Activity");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case 1000:
                    String path = Uri2PathUtil.getRealPathFromUri(mUniSDKInstance.getContext(), data.getData());
                    JSONObject object = new JSONObject();
                    object.put("path", path);
                    jsCallBack.invoke(path);
                    break;
            }
        }
    }

    @UniJSMethod
    public void showLog(String msg) {
        Log.e(TAG, msg);
    }
}
